package com.okjava.web;

import com.alibaba.fastjson.JSONObject;
import com.okjava.bean.ApiBean;
import com.okjava.util.ResponseUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Description:
 * Created @version 1.0    2016/9/22 14:25 by Benny
 */
@Controller
@RequestMapping("/api")
public class ApiController {

    public enum UrlString {
        API_ADD("api-add"),;
        private String value;

        public String getValue() {
            return value;
        }

        UrlString(String value) {
            this.value = value;
        }
    }

    /**
     * 编辑api的页面
     */
    @RequestMapping(value = "/toAdd", method = RequestMethod.GET)
    public String toAdd() {
        return UrlString.API_ADD.getValue();
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public String add(ApiBean apiBean) {
        System.out.println(JSONObject.toJSONString(apiBean));
        return "success";
    }

    @RequestMapping(value = "/getFiled", method = RequestMethod.GET)
    @ResponseBody
    public String getFields(String classWholeName) {
        String[] split = classWholeName.split("\\.");
        String className = split[split.length - 1];
        List<String> collect = null;
        try {
            Class<?> apiBean = Class.forName(classWholeName);
            Field[] declaredFields = apiBean.getDeclaredFields();
            for (Field declaredField : declaredFields) {
                //System.out.println(declaredField.getName());
            }
            String path = apiBean.getResource("").getPath() + className + ".java";
            // 替换 build/classes/main 为 src/main/java
            String src = path.replaceAll("build/classes/main", "src/main/java");
            File file = new File(src);
            collect = Files.lines(Paths.get(file.getPath()))
                    .filter(s -> {
                        return (s.trim().startsWith("//") || s.trim().startsWith("private"));
                    })
                    .map(s -> {
                        return s.trim().replaceAll("private", "").replaceAll("String", "").replaceAll("//", "").replaceAll(";", "").replaceAll("\"", "").trim();
                    })
                    .collect(Collectors.toList());
            Map<String, String> noteMap = convertListToMap(collect);
            String jsonString = convertListToJsonString(noteMap);
            //return ResponseUtil.handleJsonSuccess(jsonString);
            return jsonString;

        } catch (ClassNotFoundException | IOException e) {
            e.printStackTrace();
        }
        return ResponseUtil.handleFailed("获取属性失败");
    }

    private Map<String, String> convertListToMap(List<String> list) {
        Map<String, String> map = new HashMap<>();
        for (int i = 0; i < list.size(); i++) {
            int evenNum = i % 2 == 0 ? i : i + 1;   //偶数
            if (evenNum < list.size()) {
                map.put(list.get(evenNum), list.get(i+1));
            }
        }
        return map;
    }

    /**
     * 将 map 中的key和value 拼接成 json字符串
     * @param map
     * @return
     */
    private String convertListToJsonString(Map<String,String> map){

        JSONObject json = new JSONObject();
        String value = "";
        for (String key : map.keySet()) {
            if(map.get(key).trim().contains(">")){
                String[] splitStr = map.get(key).split(">");
                value = splitStr[splitStr.length - 1];
            }else{
                value = map.get(key).trim();
            }
            json.put(key.trim(), value);
        }
        return json.toJSONString();
    }
}
